<template>
  <div class="yoyo-container mx-auto min-h-screen bg-gray-50 pb-[60px]">
    <navBar :showMobileNavbar="false" />
    <!-- 用户信息卡片 -->
    <div class="m-4 bg-white rounded-2xl p-4 py-3 shadow-sm user-info-card" :style="cardStyle">
      <h2 class="text-xl font-semibold text-gray-800" @click="handleLogin">{{ userInfo.nickname || $t("common.pleaseLogin") }}</h2>
      <div class="flex items-center mt-1" v-if="isLoggedIn">
        <img :src="imageBaseUrl + userInfo.countryIcon" class="w-5 h-3 mr-2" />
        <span class="text-gray-600 text-sm">{{ isZh ? userInfo.countryName : userInfo.countryNameEn }}</span>
      </div>

      <!-- 探索者等级 -->
      <div class="flex items-center justify-between mt-2" v-if="isLoggedIn">
        <div class="flex-1 flex items-center mr-3">
          <img :src="imageBaseUrl + (userInfo.level && userInfo.level.icon)" class="w-5 h-3 mr-2" />
          <span class="text-blue-600 font-medium">
            {{ isZh ? userInfo.level && userInfo.level.name : userInfo.level && userInfo.level.nameEn }}
          </span>
        </div>
        <div class="text-sm text-gray-500 mt-1 flex items-center">
          {{ $t("mine.currentBalance") }}
          <span class="text-xl font-semibold text-gray-700 ml-2">{{ userInfo.point }}</span>
        </div>
      </div>
    </div>

    <!-- 个人资料 -->
    <div class="mx-4 mt-4 bg-white rounded-xl overflow-hidden shadow-sm px-4">
      <van-cell :title="$t('mine.personalInfo')" is-link @click="goTo('/user-info')" class="">
        <template #title>
          <div class="flex items-center">
            <img src="@/assets/images/mine/1.png" class="w-5 h-5 mr-1" />
            <span class="text-gray-600">{{ $t("mine.personalInfo") }}</span>
          </div>
        </template>
      </van-cell>
      <!-- 微章进度 -->
      <van-cell :title="$t('mine.myBadges')" :border="false" is-link @click="goTo('/my-badges')" class="" />
      <div class="flex items-center justify-between mt-0">
        <div class="flex items-center space-x-2">
          <div class="w-12 h-12 bg-blue-200 rounded-full flex items-center justify-center">
            <img src="@/assets/images/huizhang/徽章1.png" class="w-10 h-10" />
          </div>
          <div class="w-12 h-12 bg-white-200 rounded-full flex items-center justify-center border border-gray-200">
            <img src="@/assets/images/huizhang/徽章2.png" class="w-10 h-10" />
          </div>
          <div class="w-12 h-12 bg-white-200 rounded-full flex items-center justify-center border border-gray-200">
            <img src="@/assets/images/huizhang/3.png" class="w-10 h-10" />
          </div>
          <div class="w-12 h-12 bg-white-200 rounded-full flex items-center justify-center border border-gray-200">
            <img src="@/assets/images/huizhang/4.png" class="w-10 h-10" />
          </div>
          <div class="w-12 h-12 bg-white-200 rounded-full flex items-center justify-center border border-gray-200">
            <img src="@/assets/images/huizhang/5.png" class="w-10 h-10" />
          </div>
        </div>
      </div>
      <div class="mt-4 text-[13px] text-gray-600">
        {{ $t("mine.currentPoints") }}
        <span class="font-semibold text-[#ff7a00]">359</span>
        {{ $t("mine.points") }}，{{ $t("mine.currentLevel") }}：{{ $t("mine.explorer") }}
      </div>

      <div class="h-[1px] border-b border-gray-200 my-3 mb-2"></div>

      <!-- 我的yoyo币 -->
      <van-cell :title="$t('mine.myYoyoCoins')" is-link :border="false" @click="goTo('/yoyo-coins')" class="">
        <template #title>
          <div class="flex items-center">
            <img src="@/assets/images/mine/2.png" class="w-4 h-4 mr-2" />
            <span class="text-gray-600">{{ $t("mine.myYoyoCoins") }}</span>
          </div>
        </template>
      </van-cell>
      <div class="space-y-1 text-[13px]">
        <div class="flex">
          <span class="text-gray-600">{{ $t("mine.accumulated") }}：</span>
          <span class="font-medium">XXXX</span>
        </div>
        <div class="flex">
          <span class="text-gray-600">{{ $t("mine.used") }}：</span>
          <span class="font-medium">
            XXX
            <span class="text-gray-400">({{ $t("mine.discountRM") }}XXX)</span>
          </span>
        </div>
        <div class="flex">
          <span class="text-gray-600">{{ $t("mine.currentBalance") }}：</span>
          <span class="font-medium">
            XXX
            <span class="text-gray-400">(xxx{{ $t("mine.expireInMonths") }})</span>
          </span>
        </div>
      </div>

      <div class="h-[1px] border-b border-gray-200 my-2 mb-2"></div>

      <!-- 我的优惠券 -->
      <van-cell :title="$t('mine.myCoupons')" :border="false" is-link @click="goTo('/my-coupons')" class="" >
        <template #title>
          <div class="flex items-center">
            <img src="@/assets/images/mine/6.png" class="w-4 h-4 mr-2" />
            <span class="text-gray-600">{{ $t("mine.myCoupons") }}</span>
          </div>
        </template>
      </van-cell>
      <div class="space-y-1 text-[13px] pb-2">
        <div class="flex">
          <span class="text-gray-600">{{ $t("mine.unused") }}：</span>
          <span class="font-medium">
            {{ $t("mine.newUserRM5") }}
            <span class="text-gray-400">({{ $t("mine.validUntil2025") }})</span>
          </span>
        </div>
        <div class="flex">
          <span class="text-gray-600">{{ $t("mine.used") }}：</span>
          <span class="font-medium">2{{ $t("mine.pieces") }}</span>
        </div>
      </div>
    </div>

    <div class="mx-4 mt-4 bg-white rounded-xl overflow-hidden shadow-sm px-4">
      <van-cell :title="$t('mine.myOrders')" is-link @click="goTo('/my-orders')" class="" />
      <van-cell :title="$t('mine.reviews')" is-link @click="goTo('/my-reviews')" class="" />
      <van-cell :title="$t('mine.toDo')" is-link @click="goTo('/todo')" class="" />
      <van-cell :title="$t('mine.favorites')" is-link @click="goTo('/my-favorites')" class="" />
      <van-cell :title="$t('mine.binds')" :border="false" is-link @click="goTo('/my-binds')" class="" />
      <div class="space-y-1 text-[13px] pb-2">
        <div class="text-gray-600">{{ $t("mine.unused") }}：</div>
        <div class="text-gray-600">{{ $t("mine.used") }}：</div>
        <div class="text-gray-600">{{ $t("mine.currentBalance") }}：</div>
      </div>
    </div>

    <div class="mx-4 mt-4 bg-white rounded-xl overflow-hidden shadow-sm px-4">
      <van-cell :title="$t('mine.language')" is-link @click="dialogVisible = true" class="">
        <template #title>
          <div class="flex items-center">
            <img src="@/assets/images/mine/5.png" class="w-4 h-4 mr-1" />
            <span class="text-gray-600">{{ $t("mine.language") }}</span>
          </div>
        </template>
      </van-cell>
      <van-cell :title="$t('mine.customerService')" is-link :border="false" @click="handleCustomerService" class="" />
    </div>

    <van-tabbar route :class="['z-999 transition-transform duration-300 flex md:hidden', { 'translate-y-full': !showTabbar }]">
      <van-tabbar-item :to="item.to" v-for="item in tabbarItems" :key="item.name">
        <template #icon>
          <img :src="item.icon" class="w-14 h-14" />
        </template>
      </van-tabbar-item>
    </van-tabbar>

    <CommonDialog
      :visible.sync="dialogVisible"
      :buttons="[
        { text: '简体中文', type: 'secondary', action: 'chinese' },
        { text: 'en English', type: 'primary', action: 'english' },
      ]"
      @button-click="handleButtonClick"
      @close="handleClose">
      <div class="text-center">
        <p>
          {{ $t("home.dialog.tip.languageTitle") }}
          <br />
          {{ $t("home.dialog.tip.languageDesc") }}
        </p>
      </div>
    </CommonDialog>
  </div>
</template>

<script>
import { Cell, Image as VanImage, Tabbar, TabbarItem } from "vant"
import { getBaseInfo } from "@/apis/userInfo"
import { mapActions, mapGetters, mapMutations } from "vuex"

export default {
  name: "Mine",
  data() {
    return {
      // tabbarItems: [
      //   { name: "cart", icon: require("@/assets/images/card.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
      //   { name: "home", icon: require("@/assets/images/home.png"), to: { name: "home" }, w: 8 },
      //   { name: "yoyoCoinIntroduce", icon: require("@/assets/images/yoyo.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
      //   { name: "mine", icon: require("@/assets/images/mine.png"), to: { name: "mine" }, w: 10 },
      // ],
      baseInfo: {},
      dialogVisible: false,
      // 用户信息卡片动画状态
      userCardAnimated: false,
      // 卡片的实际高度
      cardActualHeight: "auto",
      // 滚动相关状态
      showTabbar: true,
      lastScrollTop: 0,
      scrollThreshold: 1, // 滚动阈值
    }
  },
  components: {
    [Cell.name]: Cell,
    [VanImage.name]: VanImage,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
  },
  computed: {
    ...mapGetters({
      userInfo: "auth/userInfo",
      isLoggedIn: "auth/isLoggedIn",
      isZh: "lang/isZh",
    }),
    tabbarItems() {
      return this.isZh
        ? [
            { name: "home", icon: require("@/assets/images/tabbar/home.png"), to: { name: "home" }, w: 8 },
            { name: "yoyoCoinIntroduce", icon: require("@/assets/images/tabbar/yoyo.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
            { name: "cart", icon: require("@/assets/images/tabbar/cart.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
            { name: "mine", icon: require("@/assets/images/tabbar/my-active.png"), to: { name: "mine" }, w: 10 },
          ]
        : [
            { name: "home", icon: require("@/assets/images/tabbar/home-en.png"), to: { name: "home" }, w: 8 },
            { name: "yoyoCoinIntroduce", icon: require("@/assets/images/tabbar/yoyo-en.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
            { name: "cart", icon: require("@/assets/images/tabbar/cart-en.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
            { name: "mine", icon: require("@/assets/images/tabbar/my-en-active.png"), to: { name: "mine" }, w: 10 },
          ]
    },
    imageBaseUrl() {
      return process.env.VUE_APP_IMAGE_URL
    },
    // 用户信息卡片样式
    cardStyle() {
      const fullHeight = this.cardActualHeight === "auto" ? "auto" : this.cardActualHeight + "px"
      const reducedHeight = this.cardActualHeight === "auto" ? "auto" : this.cardActualHeight * 0.8 + "px"

      return {
        height: this.userCardAnimated ? fullHeight : reducedHeight,
        opacity: this.userCardAnimated ? 1 : 0.7,
        overflow: "hidden",
        transition: "all 0.6s ease-out",
      }
    },
  },
  methods: {
    ...mapActions({
      fetchUserInfo: "auth/fetchUserInfo",
    }),
    ...mapMutations({
      setLoginDialogVisible: "auth/SET_LOGIN_DIALOG_VISIBLE",
      setIsZh: "lang/SET_IS_ZH",
    }),
    // async fetchBaseInfo() {
    //   try {
    //     const response = await getBaseInfo()
    //     // console.log('response :>> ', response);
    //     this.baseInfo = response.data
    //   } catch (error) {
    //     console.error("获取用户信息失败:", error)
    //   }
    // },
    goTo(url) {
      this.$router.push(url)
    },
    handleLanguage() {
      console.log("跳转到语言设置")
    },
    handleCustomerService() {
      console.log("跳转到客服")
    },
    handleLogin() {
      if (!this.isLoggedIn) {
        this.setLoginDialogVisible(true)
      }
    },
    handleButtonClick({ action }) {
      // 切换语言，持久化到 localStorage
      const newLang = action === "english" ? "en" : "zh-CN"
      this.$i18n.locale = newLang
      Locale.use(newLang === "en" ? "en-US" : "zh-CN", newLang === "en" ? enUS : zhCN)
      localStorage.setItem("lang", newLang)
      this.setIsZh(newLang === "zh-CN")
      // 触发界面重新渲染，以确保文本切换生效
      this.$forceUpdate()
      this.handleClose()
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 处理滚动事件 - 结合两者优点的混合逻辑
    handleScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight

      // 2. 立即更新 Tabbar 显示逻辑（实时响应，无防抖）
      this.updateTabbarVisibility(scrollTop, windowHeight, documentHeight)
    },

    // HomeHeader 滚动进度更新（来自 HomeNew.vue）
    updateHeaderScrollProgress(scrollTop) {
      // 简单的线性计算：0-80px 范围内从 0 到 1
      this.scrollProgress = Math.min(scrollTop / this.maxScrollForHeaderAnimation, 1)
    },

    // Tabbar 显示逻辑（来自 Home.vue 的简单逻辑）
    updateTabbarVisibility(scrollTop, windowHeight, documentHeight) {
      // 判断是否滚动到页面底部（距离底部50px内）
      const isNearBottom = scrollTop + windowHeight >= documentHeight - 1

      // 如果在页面底部，显示tabbar
      if (isNearBottom) {
        this.showTabbar = true
        this.lastScrollTop = scrollTop
        return
      }

      // 判断滚动方向
      const scrollDirection = scrollTop > this.lastScrollTop ? "down" : "up"

      // 只有滚动距离超过阈值才触发显示/隐藏
      if (Math.abs(scrollTop - this.lastScrollTop) > this.scrollThreshold) {
        if (scrollDirection === "down") {
          // 向下滚动，隐藏tabbar
          this.showTabbar = false
        } else {
          // 向上滚动，显示tabbar
          this.showTabbar = true
        }
        this.lastScrollTop = scrollTop
      }
    },
  },
  created() {
    // 添加滚动事件监听
    window.addEventListener("scroll", this.handleScroll, { passive: true })
    this.fetchUserInfo()
      .then((data) => {
        // console.log("data :>> ", data)
        // this.baseInfo = data || {}
      })
      .catch((error) => {
        console.error("获取用户信息失败:", error)
      })
  },
  mounted() {
    // 页面挂载后延迟触发用户信息卡片动画，确保DOM完全渲染
    console.log("Mine页面挂载，准备启动动画")
    this.$nextTick(() => {
      // 先获取卡片的实际高度
      const cardElement = this.$el.querySelector(".user-info-card")
      if (cardElement) {
        this.cardActualHeight = cardElement.offsetHeight
        console.log("卡片实际高度:", this.cardActualHeight)

        // 然后开始动画
        setTimeout(() => {
          console.log("触发用户信息卡片动画")
          this.userCardAnimated = true
          console.log("userCardAnimated状态:", this.userCardAnimated)
        }, 100) // 100ms延迟确保页面完全加载
      }
    })
  },
}
</script>

<style scoped>
/deep/.van-cell {
  padding-left: 0;
  padding-right: 0;
}
/deep/.van-tabbar-item__icon img {
  height: auto;
}

/* 用户信息卡片基础样式 */
.user-info-card {
  /* 确保动画平滑 */
  will-change: transform, opacity;
}
</style>
